package com.way.cloud.config.factory;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.util.Properties;

@Slf4j
public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) {
        log.info("Load YAML properties from {}", resource.getResource().getFilename());
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        Properties properties = factory.getObject();

        if (properties == null) {
            throw new IllegalStateException("Failed to load YAML properties from " + resource.getResource().getFilename());
        }

        String sourceName = resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, properties);
    }

}
